package com.platform.core.web.controller;

import com.google.common.base.Strings;
import com.platform.comm.util.RedisUtil;
import com.platform.comm.web.results.JsonResult;
import com.platform.comm.web.results.PageListJsonResult;
import com.platform.dto.NcloudSysOnlineUserDto;
import com.platform.uaa.controller.AuthController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.Lists;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 在线用户
 *
 * @author zq
 */
@Api(tags = "在线用户")
@RestController
@RequestMapping(name = "在线用户", path = "/management/online")
public class SysOnlineUserController extends BaseController {

    private final RedisUtil redisUtil;

    public SysOnlineUserController(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    /**
     * 分页查询
     */
    @ApiOperation("在线用户")
    @PostMapping(name = "在线用户", path = "/search")
    public PageListJsonResult<NcloudSysOnlineUserDto> search(@RequestBody NcloudSysOnlineUserDto dto) {
        String userName = dto.getUserName();
        String departName = dto.getDepartName();
        Collection<String> keys = redisUtil.keys(AuthController.LOGIN_TOKEN_KEY.concat("*"));
        List<Object> listValue = redisUtil.getListValue(keys);
        List<NcloudSysOnlineUserDto> onLineUsers = Lists.newArrayList();
        for (Object value : listValue) {
            NcloudSysOnlineUserDto user = (NcloudSysOnlineUserDto) value;
            if (!Strings.isNullOrEmpty(userName) && !Strings.isNullOrEmpty(departName)) {
                if (user.getUserName().contains(userName) && user.getDepartName().contains(departName)) {
                    onLineUsers.add(user);
                }
            } else if (!Strings.isNullOrEmpty(userName)) {
                if (user.getUserName().contains(dto.getUserName())) {
                    onLineUsers.add(user);
                }
            } else if (!Strings.isNullOrEmpty(departName)) {
                if (user.getDepartName().contains(dto.getDepartName())) {
                    onLineUsers.add(user);
                }
            } else {
                onLineUsers.add(user);
            }
        }
        return new PageListJsonResult<>(onLineUsers, onLineUsers.size());
    }

    /**
     * 强退用户
     */
    @ApiOperation("强退用户")
    @PostMapping(name = "强退用户", path = "/forceLogout")
    public JsonResult forceLogout(@RequestBody Map<String, String> map) {
        String tokenId = map.get("tokenId");
        redisUtil.del(AuthController.LOGIN_TOKEN_KEY + tokenId);
        return JsonResult.success();
    }

}
